package cn.nextapp.app.bbs;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Properties;

import cn.nextapp.app.bbs.api.*;
import cn.nextapp.app.bbs.common.AppConfigHelper;
import cn.nextapp.app.bbs.entity.URLs;
import android.app.Application;
import android.content.Context;

/**
 * NextApp 的应用扩展信息
 * @author Winter Lau
 * @date 2011-12-17 下午10:17:51
 */
public class NextAppContext extends Application {

	private URLs urls = null; //全局接口URL定义
	private boolean login = false;	//登录状态
	private Hashtable<String, Object> memCacheRegion = new Hashtable<String, Object>();

	public boolean isLogin() {
		return login;
	}

	public void setLogin(boolean login) {
		this.login = login;
	}

	public URLs getUrls() throws ApiException {
		if(urls == null) {
			urls = NextAppClient.urls(this.getString(R.string.app_api_url));
		}
		return urls;
	}

	public void setUrls(URLs urls) {
		this.urls = urls;
	}
	
	/**
	 * 将对象保存到内存缓存中
	 * @param key
	 * @param value
	 */
	public void setMemCache(String key, Object value) {
		memCacheRegion.put(key, value);
	}
	
	/**
	 * 从内存缓存中获取对象
	 * @param key
	 * @return
	 */
	public Object getMemCache(String key){
		return memCacheRegion.get(key);
	}
	
	/**
	 * 保存磁盘缓存
	 * @param key
	 * @param value
	 * @throws IOException
	 */
	public void setDiskCache(String key, String value) throws IOException {
		FileOutputStream fos = null;
		try{
			fos = openFileOutput("cache_"+key+".data", Context.MODE_PRIVATE);
			fos.write(value.getBytes());
			fos.flush();
		}finally{
			try {
				fos.close();
			} catch (Exception e) {}
		}
	}
	
	/**
	 * 获取磁盘缓存数据
	 * @param key
	 * @return
	 * @throws IOException
	 */
	public String getDiskCache(String key) throws IOException {
		FileInputStream fis = null;
		try{
			fis = openFileInput("cache_"+key+".data");
			byte[] datas = new byte[fis.available()];
			fis.read(datas);
			return new String(datas);
		}finally{
			try {
				fis.close();
			} catch (Exception e) {}
		}
	}

	public void setProperties(Properties ps){
		AppConfigHelper.getAppConfig(this).set(ps);
	}

	public Properties getProperties(){
		return AppConfigHelper.getAppConfig(this).get();
	}
	
	public void setProperty(String key,String value){
		AppConfigHelper.getAppConfig(this).set(key, value);
	}
	
	public String getProperty(String key){
		return AppConfigHelper.getAppConfig(this).get(key);
	}
	public void removeProperty(String...key){
		AppConfigHelper.getAppConfig(this).remove(key);
	}
}
